package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Transactional
    @Override
    public void submit(Orders orders) {

        // 1. 数据准备
        // 1.1 更具用户id查询购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);

        // 1.2 查询地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        // 1.3 根据用户id查询当前用户
        User user = userService.getById(BaseContext.getCurrentId());

        // 2. 组装订单详情表数据
        // 雪花算法，生成订单表id值
        long orderId = IdWorker.getId();
        List<OrderDetail> orderDetailList = new ArrayList<>();
        BigDecimal amount = new BigDecimal("0");
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();

            BeanUtils.copyProperties(shoppingCart, orderDetail);
            // 购物车中没有  订单表id
            orderDetail.setOrderId(orderId);

            // 计算实际金额
            amount = amount.add(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())));

            orderDetailList.add(orderDetail);
        }

        // 3. 组装订单表
        orders.setId(orderId);  // 订单id
        orders.setNumber(String.valueOf(orderId));  //订单号
        orders.setStatus(2);  // 订单状态，默认派送中
        orders.setUserId(BaseContext.getCurrentId()); // 用户id
        orders.setOrderTime(LocalDateTime.now());  // 下单时间
        orders.setCheckoutTime(LocalDateTime.now()); // 结账时间
        orders.setAddress(addressBook.getDetail());  // 地址信息
        orders.setConsignee(addressBook.getConsignee()); // 收件人
        orders.setPhone(addressBook.getPhone()); // 收件人手机
        orders.setUserName(user.getName()); // 下单人
        orders.setAmount(amount);  // 实收金额

        // 4. 添加数据
        orderDetailService.saveBatch(orderDetailList);

        this.save(orders);

        // 5. 清空购物信息
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

    }

    @Transactional
    @Override
    public void again(Orders orders) {
        // 1. 根据订单id 查询订单明细
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(orders.getId() != null, OrderDetail::getOrderId, orders.getId());

        List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);

        // 2. 将订单明细表中数据添加到购物车表中
        List<ShoppingCart> shoppingCarts = orderDetailList.stream().map(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);

            // 需要自行填充 用户id 和创建时间
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 3. 判断购物车中有没有相同的数据，有相同的数据，数量相加，不相同添加数据
        for (ShoppingCart shoppingCart : shoppingCarts) {
            // 根据用户id 和  菜品/套餐查询
            LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
            // 判断当前是菜品还是套餐
            if (shoppingCart.getDishId() != null) {
                // 菜品
                shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getDishId, shoppingCart.getDishId());
            } else {
                // 套餐
                shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
            }

            // 一个用户一个 菜品/套餐 只可能存在一份数据
            ShoppingCart one = shoppingCartService.getOne(shoppingCartLambdaQueryWrapper);

            // 判断是否有数据
            if (one != null) {
                // 更新数量
                shoppingCart.setNumber(shoppingCart.getNumber() + one.getNumber());
                shoppingCartService.updateById(shoppingCart);
            } else {
                // 添加数据
                shoppingCartService.save(shoppingCart);
            }
        }
    }
}
